package com.cloud.zuul;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.netflix.zuul.http.ServletInputStreamWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AutoWiredTimeFilter extends ZuulFilter {
    private static Logger log = LoggerFactory.getLogger(AutoWiredTimeFilter.class);
    /*
    filterType：返回一个字符串代表过滤器的类型，
    在zuul中定义了四种不同生命周期的过滤器类型，具体如下：
    pre：路由之前
    routing：路由之时
    post： 路由之后
    error：发送错误调用
    */
    @Override
    public String filterType() {
        return "pre";
    }

    /*filterOrder：过滤的顺序*/
    @Override
    public int filterOrder() {
        return 0;
    }

    /*shouldFilter：这里可以写逻辑判断，是否要过滤，本文true,永远过滤。*/
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /*run：过滤器的具体逻辑。可用很复杂，包括查sql，nosql去判断该请求到底有没有权限访问。*/
    @Override
    public Object run() throws ZuulException {

        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String method = request.getMethod();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
//        if ("GET".equals(method)){
//            request.getParameterMap();// 关键步骤，一定要get一下,下面这行代码才能取到值
//            Map<String, List<String>> requestQueryParams = ctx.getRequestQueryParams();
//            if (requestQueryParams == null) {
//                requestQueryParams = new HashMap<>();
//            }
//            List<String> values = new ArrayList<>();
//            values.add(LocalDateTime.now().toString());
//            System.out.println(requestQueryParams);
//            requestQueryParams.put("dtCreateTime",values);
//            ctx.setRequestQueryParams(requestQueryParams);
//        }
        log.info("ok");
        return null;
    }

    public static void main(String[] args) {
        System.out.println(LocalDateTime.now().toString());
    }
}
